package org.nokatag.dbgrid;

import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.nokatag.password.AESPlus;
import org.nokatag.system.BugInfoWrint;
import org.nokatag.system.Concest;
import org.nokatag.system.DBCon;
import org.nokatag.system.RunUserFunction;

/**
 * DBGrid子表ajax加载
 * @author xiefangjian
 *
 */
public class AjaxSubGrid {
	public static void newBody(HttpServletRequest request,HttpServletResponse response){
		String dou=request.getParameter("do");
		String body="";
		if(dou!=null && dou.equalsIgnoreCase("sql")){
			body= sqlType(request,response);
		}else if(dou!=null && dou.equalsIgnoreCase("cl")){
			body= Rclass(request,response);
		}
		try{
			OutputStream out = response.getOutputStream();
			Writer wr=new OutputStreamWriter(out,Concest.ENCODING);
			wr.write(body);
			wr.flush();
			out.flush();
			wr.close();
			out.close();
		}catch(Exception e){
			BugInfoWrint.Print(e);
		}
		
		
	}
	//----------------sql方式加载---------------------------------------------------------
	public static String sqlType(HttpServletRequest request,HttpServletResponse response){
		StringBuffer body = new StringBuffer();
		try{
			Connection con = DBCon.getCon();
			String sql=request.getParameter("noka_subsql");
			String subformatcell=request.getParameter("noka_subformatcell");//子表格式化
			String[] noka_subsqlwhere=request.getParameterValues("noka_subsqlwhere");//查询参数
			
			if(sql!=null){
				sql=AESPlus.decrypt(sql,Concest.SQLKEY);
				PreparedStatement pa= con.prepareStatement(sql,ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);
				if(noka_subsqlwhere!=null && noka_subsqlwhere.length>0){
					int i=1;
					for(String c:noka_subsqlwhere){
						pa.setObject(i++,c);
					}
				}
				ResultSet rsf=pa.executeQuery();
				ResultSetMetaData rsmdsubtable = rsf.getMetaData(); // 取得列名对像
				Integer cellsn = rsmdsubtable.getColumnCount();//列数
				body.append("<table class=\"subgrid_table\">");
				//--------------------生成列名-------------------------------------------------------------------------------
				List<String> cellName=new ArrayList<String>();//列名
				body.append("<tr class=\"subgrid_head_tr\">");
				for (int cellin = 1; cellin <=cellsn; cellin++) {
					body.append("<td class=\"subgrid_head_td\">"+ rsmdsubtable.getColumnName(cellin)+ "</td>");
					cellName.add(cellin-1, rsmdsubtable.getColumnName(cellin));
				}
				body.append("</tr>");
				//---------------------生成自定义方法的map-------------------------------------------------------------------
				Map<String,String> fmap =new HashMap<String, String>();//自定义方法map
				if(subformatcell!=null && subformatcell.trim().length()>0){
					subformatcell=AESPlus.decrypt(subformatcell,Concest.SQLKEY);//解密
					for(String fun:subformatcell.split("\\|")){
						fun=fun.trim();
						String cn = fun.substring(fun.indexOf(" as ")+" as ".length(),fun.length());
						fmap.put(cn, fun.split(" as ")[0]);//加入方法
					}
				}
				//---------------------生成数据----------------------------------------------------------------------------
				int a=0;
				while (rsf.next()) {//行数据
					if(a%2==0)//偶数行
						body.append("<tr class=\"subgrid_cell_tr_0\">");
					else
						body.append("<tr class=\"subgrid_cell_tr_1\">");
					//--------------------单元格数据-----------------------------------------------------------------------
					Map<String,Object> datam=new HashMap<String, Object>();//单元格数据
					for(int i=0;i<cellName.size();i++){
						datam.put(cellName.get(i), rsf.getString(cellName.get(i)));
					}
					//--------------------生成显示数据---------------------------------------------------------------------
					for (int i=0;i<cellName.size();i++) {
						String cname=cellName.get(i);
						String value=datam.get(cname)==null?"&nbsp;":datam.get(cname).toString();
						if(fmap.get(cname)!=null && fmap.get(cname).trim().length()>0 && datam.get(cname)!=null){
							value=RunUserFunction.TagFunction(fmap.get(cname).trim(), request, datam);
						}
						if(a%2==0)//偶数行
							body.append("<td class=\"subgrid_cell_0\">"+ (value==null?"&nbsp;":value)+ "</td>");
						else//奇数行
							body.append("<td class=\"subgrid_cell_1\">"+ (value==null?"&nbsp;":value)+ "</td>");
					}
					body.append("</tr>");
					a++;
				}
				body.append("</table>");
				rsf.close();
				pa.close();
			}
		}catch(Exception se){
			BugInfoWrint.Print(se);
		}
		return body.toString();
	}
	//----------------自定义方式加载-----------------------------------------------------
	public static String Rclass(HttpServletRequest request,HttpServletResponse response){
		String[] noka_sub_data=request.getParameterValues("noka_sub_data");//数据
		String[] noka_sub_cell=request.getParameterValues("noka_sub_cell");//列名
		String noka_sub_subtable=request.getParameter("noka_sub_subtable");//子表参数
		String noka_sub_i=request.getParameter("noka_sub_i");//行号
		Map<String,Object> map=new HashMap<String,Object>();
		if(noka_sub_data!=null && noka_sub_data.length>0){
			int i=0;
			for(String kv:noka_sub_data){
				map.put(noka_sub_cell[i++],kv);
			}
		}
		
		List<String> cell=new ArrayList<String>();
		if(noka_sub_cell!=null && noka_sub_cell.length>0){
			for(String v:noka_sub_cell){
				cell.add(v);
			}
		}
		noka_sub_subtable=AESPlus.decrypt(noka_sub_subtable,Concest.SQLKEY);
		String body=DBCon.getCon(noka_sub_subtable, Integer.parseInt(noka_sub_i), map, cell);
		return body;
	}
}
